#
# Examples for get all files uploades in "contagiominidump.blogspot.com" repository
#

import sys, getopt, os, datetime
import urlparse, httplib
import MediaFire

API_KEY = "SET_YOUR_API_KEY"
APP_ID  = "HERE_YOUR_APP_ID"

def donwload(url, name, path, vervose):
	if not path.endswith('/'):
		path += '/'
	headers = {
		"Accept": "*/*",
		"UserAgent":"ehooo's MediaFire Python API Wrapper -ContagioDump Sample-"
	}

	parseUrl = urlparse.urlparse(url)
	host = parseUrl.netloc
	if parseUrl.hostname:
		host = parseUrl.hostname
	if parseUrl.port:
		host += ":"+parseUrl.port

	conn = None
	if parseUrl.port == 443 or parseUrl.scheme == 'https':
		conn = httplib.HTTPSConnection(host)
	else:
		conn = httplib.HTTPConnection(host)

	conn.request("GET",parseUrl.path+"?"+parseUrl.query, None, headers)
	response = conn.getresponse()
	head = response.getheaders()
	location = response.getheader('location',False)
	if location:
		if vervose:
			print "Rediretion to",location
		conn.close()
		donwload(location, name, path, vervose)
		return
	if vervose:
		print "Recive HEADERS ->",head

	if response.status == httplib.OK:
		chuck = 1024
		with open(path+name, 'wb') as f:
			r = response.read(chuck)
			while len(r) == chuck:
				f.write(r)
				r = response.read(chuck)
			f.write(r)
			f.close()
		conn.close()
		return
	text = response.read()
	conn.close()
	raise IOError(response.status, head)

def usage():
	print sys.argv[1]," options:"
	print "-d|--date= YYYY-MM-DD HH:MM:SS"
	print "-o|--output= PATH"
	print "-b|--block"
	print "-v|--verbose 0|1|2"
	print "-u|--user USER_EMAIL"
	print "-p|--password USER_PASSWORD"

if __name__ == '__main__':
	try:
		opts, args = getopt.getopt(
			sys.argv[1:],
			"d:o:hbv:u:p:",
			["date=", "output=", "help", "block","verbose=","user=","password="]
		)
	except getopt.GetoptError, err:
		print str(err)
		usage()
		sys.exit(2)
	last_check = None
	output = os.getcwd()
	verbose = 0
	block = False
	user = None
	password = None
	for o, a in opts:
		if o in ("-v", "--verbose"):
			verbose = int(a)
		elif o in ("-d", "--date"):
			last_check = datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S")
		elif o in ("-h", "--help"):
			usage()
			sys.exit()
		elif o in ("-o", "--output"):
			output = os.path.abspath(a)
		elif o in ("-b", "--block"):
			block = True
		elif o in ("-u", "--user"):
			user = a
		elif o in ("-p", "--password"):
			password = a
		else:
			assert False, "unhandled option"

	auth_user = None
	if user and password:
		auth_user = MediaFire.MediaFireUser(APP_ID, API_KEY)
		auth_user.get_session_token(user, password)
		if verbose  >= 1:
			print "Recive session", auth_user.session_token()

	mobile_malware = MediaFire.MediaFireFolder('78npy8h7h0g9y', auth_user)
	if verbose  >= 1:
		print mobile_malware.get_info(),"\n\n"
		print mobile_malware.get_revision(),"\n\n"

	chuck = 1
	content = mobile_malware.get_content('files','created','desc', chuck)
	block_list = []
	last_new = None
	while content['content_type'] in content:

		for file_data in content[ content['content_type'] ]:
			if not last_new:
				last_new = datetime.datetime.strptime(file_data['created'], "%Y-%m-%d %H:%M:%S")

			if last_check:
				t = datetime.datetime.strptime(file_data['created'], "%Y-%m-%d %H:%M:%S")
				if t < last_check:
					break

			if not block:
				f = MediaFire.MediaFireFile(file_data['quickkey'], auth_user)
				links = f.get_links('normal_download')['links']
				for l in links:
					url = l['normal_download']
					name = file_data['filename']
					if verbose >= 1:
						print file_data['created'] ,name,"->",url
					donwload(url, name, output, (verbose>=2))
				print "\n"
			else:
				block_list.append(file_data['quickkey'])
		if len(block_list) > 0:
			f = MediaFire.MediaFireFile(block_list)
			links = f.get_links('normal_download')['links']
			for l in links:
				url = l['normal_download']
				name = l['quickkey']
				if verbose >= 1:
					print name,"->",url
				donwload(url, name, output, (verbose>=2))
			print "\n"

		chuck += 1
		content = mobile_malware.get_content('files','created','asc', chuck)
	print last_new

	exit()



